<?php


namespace app\live\controller\v3;

use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\live\LiveAnswerDiceRecord;
use app\common\cachemodel\live\LiveAnswerReward;
use app\common\cachemodel\live\LiveAnswerScore;
use app\common\cachemodel\live\LiveAnswerTarotRecord;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\Util;
use app\common\model\Divination;
use app\live\controller\LiveAuth;
use think\Env;

class LiveActive extends LiveAuth
{
    /**
     * 获取直播记录详情
     */
    public function getLiveRecordDetail()
    {
        $id = input('id/d');

        if (empty($id))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $data = (new LiveRecordingInfo())->getRecordDetail($this->liveInfo['live_id'], $id);

        if ($data)
        {
            return show(config('code.success'), '请求成功', $data);
        } else
        {
            return show(config('code.error'), '直播记录不存在～');
        }
    }

    /**
     * 获取数据总览详情
     */
    public function getAllDetail()
    {
        $startTime = trim(input('start_time/s', ''));
        $endTime = trim(input('end_time/s', ''));

        $startTime .= ' 00:00:00';
        $endTime .= ' 23:59:59';

        $st = strtotime($startTime);
        $et = strtotime($endTime);

        if (empty($startTime) || empty($endTime) || date('Y-m-d H:i:s', $st) !== $startTime || date('Y-m-d H:i:s', $et) != $endTime)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($st >= $et)
        {
            return show(config('code.error'), '结束必须大于开始时间');
        }

        $data = (new LiveRecordingInfo())->getTimeRangeDetail($this->liveInfo['live_id'], $startTime, $endTime);

        if ($data)
        {
            return show(config('code.success'), '请求成功', $data);
        } else
        {
            return show(config('code.error'), '直播记录不存在～');
        }
    }

    /**
     * 获取解答历史
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAnswerList()
    {
        $live_record_id = input('live_record_id/d', 0);
        $type = input('type/d', 1);

        $where['answer_end_rid'] = $live_record_id;
        if ($type === 1)
        {
            $where['price'] = ['>', 0];
        } else
        {
            $where['price'] = 0;
        }
        $where['status'] = ['in', [6, 8, 9, 10]];
        //获取看盘数据
        $astroData = (new LiveAnswerAstroRecord())->getRecordAnswerList($where, 1);
        $astroId = $astroData['ids'];
        $astro = $astroData['data'];

        //获取骰子数据
        $diceData = (new LiveAnswerDiceRecord())->getRecordAnswerList($where, 2);
        $diceId = $diceData['ids'];
        $dice = $diceData['data'];

        //获取塔罗数据
        $tarotData = (new LiveAnswerTarotRecord())->getRecordAnswerList($where, 3);
        $tarotId = $tarotData['ids'];
        $tarot = $tarotData['data'];

        $answerIds = array_merge($astroId, $diceId, $tarotId);
        array_multisort(array_column($answerIds, 'cancel'), SORT_NUMERIC, SORT_DESC, $answerIds);// 按 create_time 排序

        $data = [
            'total' => count($answerIds),
            'per_page' => 1,
            'current_page' => 1,
            'last_page' => 1,
            'data' => []
        ];
        $statusTxt = [
            6 => '已完成',
            8 => '已取消',
            9 => '已拒绝',
            10 => '已取消',
        ];
        foreach ($answerIds as $item)
        {
            $create_time = date('Y-m-d H:i:s', $item['cancel']);
            $evaluateStatus = 0;
            $status = 0;
            switch ($item['type'])
            {
                case 1:
                    $title = '看盘解答';
                    $question = $astro[$item['id']]['question'];
                    $price = $astro[$item['id']]['price'];
                    $status = (int)$astro[$item['id']]['status'];
                    $evaluateStatus = (int)$astro[$item['id']]['evaluate_status'];
                    $duration = (int)$astro[$item['id']]['duration'];
                    break;
                case 2:
                    $title = '骰子解答';
                    $question = $dice[$item['id']]['question'];
                    $price = $dice[$item['id']]['price'];
                    $status = (int)$dice[$item['id']]['status'];
                    $evaluateStatus = (int)$dice[$item['id']]['evaluate_status'];
                    $duration = (int)$dice[$item['id']]['duration'];
                    break;
                case 3:
                    $title = '塔罗解答';
                    $question = $tarot[$item['id']]['question'];
                    $price = $tarot[$item['id']]['price'];
                    $status = (int)$tarot[$item['id']]['status'];
                    $evaluateStatus = (int)$tarot[$item['id']]['evaluate_status'];
                    $duration = (int)$tarot[$item['id']]['duration'];
                    break;
            }
            if ($status === 6 && $evaluateStatus === 1)
            {
                $statusDes = '已评价';
            } else
            {
                $statusDes = $statusTxt[$status];
            }

            $data['data'][] = [
                'id' => $item['id'],
                'title' => $title ?? '',
                'question' => $question ?? '',
                'price' => $price ?? 0,
                'create_time' => $create_time,
                'type' => $item['type'],
                'target' => 'local',
                'link' => "liver_page?page=answer_detail&id={$item['id']}&type={$item['type']}",
                'status_des' => $statusDes,
                'duration' => $duration ?? 0
            ];
        }
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取解答历史详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAnswerDetail()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);

        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '解答类型异常');
        }
        $answerModel = null;
        switch ($type)
        {
            case 1:
                $answerModel = new LiveAnswerAstroRecord();
                break;
            case 2:
                $answerModel = new LiveAnswerDiceRecord();
                break;
            case 3:
                $answerModel = new LiveAnswerTarotRecord();
                break;
        }
        $history = $answerModel->getInfoById($id);
        if (!$history)
        {
            return show(config('code.error'), '解答不存在');
        }

        $data = [];
        //区分付费与免费
        $statusTxt = [
            1 => '待支付',
            2 => '等待解答',
            3 => '待响应',
            4 => '未响应',
            5 => '解答中',
            6 => '已完成',
            7 => '用户超时未支付取消',
            8 => '用户已取消',
            9 => '主播已拒绝',
            10 => '用户超时响应已取消',
        ];
        if ($history['price'] > 0)
        {
            $data['common_progress'] = [
                'current_index' => 4,
                'list' => ['申请成功', '等待解答', '用户响应', '解答中', '完成']
            ];
            $data['common_list'] = [
                [
                    'type' => 1,
                    'title' => '数据详情',
                    'desc' => ''
                ],
                [
                    'type' => 2,
                    'title' => '用户下单时间：',
                    'desc' => date('Y-m-d H:i', $history['create_time'])
                ], [
                    'type' => 2,
                    'title' => '订单编号：',
                    'desc' => $history['order_num']
                ], [
                    'type' => 2,
                    'title' => '解答时间：',
                    'desc' => date('Y-m-d H:i', $history['start_time'])
                ], [
                    'type' => 2,
                    'title' => '解答完成：',
                    'desc' => date('Y-m-d H:i', $history['cancel'])
                ], [
                    'type' => 2,
                    'title' => '解答时长：',
                    'desc' => Sec2Time($history['duration'])
                ], [
                    'type' => 2,
                    'title' => '价格：',
                    'desc' => $history['price'] . '元'
                ], [
                    'type' => 2,
                    'title' => '状态：',
                    'desc' => $statusTxt[$history['status']]
                ],
            ];
            //获取评价信息
            $eva = (new LiveAnswerScore())->where(['answer_id' => $id])->field('star,reason')->find();
            $data['common_evaluate'] = [
                'star_index' => $eva['star'] ?? 0,
                'content' => $eva['reason'] ?? '',
                'title' => '用户评价',
            ];
        } else
        {
            $data['common_list'] = [
                [
                    'type' => 1,
                    'title' => '数据详情',
                    'desc' => ''
                ],
                [
                    'type' => 2,
                    'title' => '用户申请时间：',
                    'desc' => date('Y-m-d H:i', $history['create_time'])
                ], [
                    'type' => 2,
                    'title' => '解答时间：',
                    'desc' => date('Y-m-d H:i', $history['start_time'])
                ], [
                    'type' => 2,
                    'title' => '解答完成：',
                    'desc' => date('Y-m-d H:i', $history['cancel'])
                ], [
                    'type' => 2,
                    'title' => '解答时长：',
                    'desc' => Sec2Time($history['duration'])
                ], [
                    'type' => 2,
                    'title' => '用户打赏：',
                    'desc' => (new LiveAnswerReward())->getUserAnswerReward($type, $history['id']) . '准币'
                ], [
                    'type' => 2,
                    'title' => '状态：',
                    'desc' => $statusTxt[$history['status']]
                ],
            ];
        }

        if ($history['cancel_reason'])
        {
            $data['common_list'][] = [
                'type' => 2,
                'title' => '取消原因：',
                'desc' => $history['cancel_reason']
            ];
        }

        $data['common_question_list'] = [
            [
                'title' => '我的问题',
                'desc' => $history['question']
            ]
        ];
        switch ($type)
        {
            case 1:
                $recodeList = [];
                $recode = json_decode($history['extend'], true);
                if (isset($recode['recode1']) && $recode['recode1'])
                {
                    $recodeList[] = [
                        'id' => $recode['recode1']['id'],
                        'name' => $recode['recode1']['name'],
                        'type' => $recode['recode1']['type'] == 1 ? 1 : 2,
                        'age' => '年龄' . birthday($recode['recode1']['year'] . '-' . $recode['recode1']['month'] . '-' . $recode['recode1']['day']),
                        'comments' => $recode['recode1']['comments']
                    ];
                }
                if (isset($recode['recode2']) && $recode['recode2'])
                {
                    $recodeList[] = [
                        'id' => $recode['recode2']['id'],
                        'name' => $recode['recode2']['name'],
                        'type' => $recode['recode2']['type'] == 1 ? 1 : 2,
                        'age' => '年龄' . birthday($recode['recode2']['year'] . '-' . $recode['recode2']['month'] . '-' . $recode['recode2']['day']),
                        'comments' => $recode['recode2']['comments']
                    ];
                }

                //星盘地址
                $astro_url=Util::getAstroUrlFromRecords($this->request->header(),$recode);

                $data['astro_data'] = [
                    'title' => '档案',
                    'recode_list' => $recodeList,
                    'astro_url' => $astro_url,
                ];
                $data['common_question_list'][] = [
                    'title' => '我的问题描述',
                    'desc' => $history['question_des']
                ];
                break;
            case 2:
                $diceInfo = (new Divination())->getDetail(['id' => $history['history_id']]);
                $data['dice_data'] = [
                    'title' => '结果',
                    'dice' => [
                        'planet' => $diceInfo['planet'],
                        'sign' => $diceInfo['sign'],
                        'house' => $diceInfo['house'],
                    ]
                ];
                break;
            case 3:
                $tarotRecordModel = new ZlTarotRecords();
                $tarot = $tarotRecordModel->getInfoById($history['history_id']);
                $detail = $tarotRecordModel->getDetails($tarot);
                $data['tarot_data'] = [
                    'title' => '结果',
                    'tarot_cards' => $detail['tarot_cards']
                ];
                break;
        }
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取取消原因列表
     * @return \think\response\Json
     */
    public function getCancelList()
    {
        $data = config('live_app.live_cancel_list');
        return show(config('code.success'), '获取成功', array_values($data));
    }
}
